<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { defaultFormData } from './index'
import type {
  EnergyDiscountInfo,
  SaveOrUpdateIndicatorParams,
} from '@/types'
import { energyDiscountApi, indicatorApi } from '@/api'
import CustomDialog from '@/components/CustomDialog/CustomDialog.vue'
import { useMixinQueryIndicatorDicts } from '@/mixins/MixinQueryIndicatorDicts'

const props = defineProps<{
  title: string
  unitData: any[]
}>()
const emits = defineEmits<{
  success: []
}>()
const pointInfo = inject<Ref<any>>('pointInfo')
const toolInfo = inject<Ref<any>>('toolInfo')
const [treeData, setTreeData] = useState<any[]>([])

const formData = defineModel<SaveOrUpdateIndicatorParams>({
  default: () => defaultFormData,
})

const [energyDiscountData, setEnergyDiscountData]
  = useState<EnergyDiscountInfo[]>([])

const rules = {
  pointId: [{ required: true, message: '必填项' }],
  indicatorName: [{ required: true, message: '必填项' }],
  indicatorCode: [{ required: true, message: '必填项' }],

  indicatorType: [{ required: true, message: '必填项' }],
  measuringPointNumber: [
    { required: true, message: '必填项' },
  ],

  unitId: [{ required: true, message: '必填项' }],
  indicatorMultiple: [{ required: true, message: '必填项' }],
  // isVirtually: [{ required: true, message: '必填项' }],
  // energyId: [{ required: true, message: '必填项' }]
}
const inputable = ref(false)
watch(
  () => unref(inputable),
  () => {
    unref(formData).indicatorName = ''
  },
)

/** 指标类别与统计类型的联动 */
const statisticalType = computed(() => {
  const { indicatorType } = toValue(formData)
  if (!indicatorType) {
    return ''
  }
  // 指标类型为 "用量" 时，统计类型为 "累加"
  return Number(indicatorType) === 1 ? '1' : '2'
})
/** 指标类别与虚拟指标的联动 */
const virtually = computed(() => {
  const { indicatorType } = toValue(formData)
  // 只有指标类型为 "用量" 时，才可能存在 "虚拟指标"
  return Number(indicatorType) === 1
})
/**
 * 虚拟指标没有单位、倍率、能源品种
 * 统计类型为“表头”没有倍率、能源品种，即指标类别是非用量
 */

const formRef = ref<FormInstance>()
const dialogRef = ref<InstanceType<
  typeof CustomDialog
> | null>(null)

async function getEnergyDiscountData() {
  try {
    const { data: res }
      = await energyDiscountApi.queryList()
    if (!res) {
      setEnergyDiscountData([])
      return
    }
    setEnergyDiscountData(res)
  }
  catch (e) {}
}

async function clickSave(done: () => void) {
  try {
    const isValid = await formRef.value
      ?.validate()
      .catch(() => {})

    if (!isValid)
      return
    const params = {
      ...toValue(formData),
      statisticalType: statisticalType.value,
      statisticalName: ['', '累加', '表头'][
        +statisticalType.value
      ],
    }
    if (!params.id) {
      params.source = 1
    }

    // @ts-expect-error 忽略类型检查
    delete params.indicatorTypeName
    await indicatorApi.saveOrUpdateIndicator(params)

    ElMessage.success('保存成功')
    done()
    close()
    emits('success')
  }
  catch (e) {
  }
  finally {
    done()
  }
}

const { indicatorDicts, getIndicatorDicts, getKeyFromValue }
  = useMixinQueryIndicatorDicts()

function open() {
  dialogRef.value?.open()
}

function close() {
  dialogRef.value?.close()
}
function handlerMeasuringPointNumber(val: string) {
  formData.value.indicatorNumber = `${pointInfo?.value?.pointCode}.MI.${toolInfo?.value?.code}.${val}`
}
async function getTreeData() {
  const { data: res } = await pointApi.loadRoleEnergyUnit()
  setTreeData(res.list ?? [])
}
function handleUnitChange() {
  const unitList = props.unitData
    .map(item => item.unitList)
    .flat()
  const unit = unitList.find(
    item => item.id === formData.value.unitId,
  )
  if (!unit)
    return
  formData.value.unit = unit.unitName
}

function changeIndicatorDict() {
  const value = unref(formData).indicatorName
  if (value) {
    const key = getKeyFromValue(value)
    if (key) {
      formData.value.measuringPointNumber = key
    }
  }
}

watch(
  () => unref(formData).measuringPointNumber,
  (val: string) => {
    handlerMeasuringPointNumber(val || '')
  },
)
onMounted(() => {
  // 接口将废弃
  // getEnergyDiscountData();
  getTreeData()
  getIndicatorDicts()
})

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    width="640px"
    no-scroll
    :title="title"
    need-saving
    @confirm="clickSave"
  >
    <ElForm
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
    >
      <!-- <ElDivider>基本信息</ElDivider> -->
      <ElFormItem label="用能单元" prop="pointId">
        <ElCascader
          v-model="formData.pointId"
          :options="treeData"
          :props="{
            value: 'id',
            label: 'pointName',
            children: 'children',
            checkStrictly: true,
            emitPath: false,
          }"
          clearable
          disabled
          placeholder="请选择用能单元"
          style="width: 100%"
        />
      </ElFormItem>
      <ElFormItem label="指标名称" prop="indicatorName">
        <ElSelect
          v-if="!inputable"
          v-model="formData.indicatorName"
          placeholder="请输入指标名称"
          :maxlength="50"
          :minlength="2"

          clearable default-first-option
          @change="changeIndicatorDict"
        >
          <ElOption
            v-for="item in indicatorDicts"
            :key="item"
            :label="item"
            :value="item"
          />
        </ElSelect>
        <ElInput
          v-else
          v-model="formData.indicatorName"
          maxlength="50"
          placeholder="请输入指标名称"
          clearable
        />
        <ElCheckbox
          v-model="inputable"
          class="ggg-checkbox"
          label="勾选后可自定义输入指标名称"
        />
      </ElFormItem>
      <ElFormItem
        label="测点编码"
        prop="measuringPointNumber"
      >
        <ElInput
          v-model.trim="formData.measuringPointNumber"
          maxlength="50"
          placeholder="请输入测点编码"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="指标编码">
        <ElInput
          v-model.trim="formData.indicatorNumber"
          maxlength="50"
          placeholder="请输入指标编码"
          disabled
          clearable
        />
      </ElFormItem>
      <ElFormItem label="测点点位号" prop="indicatorCode">
        <ElInput
          v-model.trim="formData.indicatorCode"
          maxlength="20"
          placeholder="请输入测点点位号"
          clearable
        />
      </ElFormItem>
      <!-- <ElDivider>类型</ElDivider>
      <ElFormItem label="指标类别" prop="indicatorType">
        <DictionaryPicker
          v-model="formData.indicatorType"
          code="ZHI_BIAO_LEI_BIE"
          placeholder="请选择指标类别"
          clearable
        ></DictionaryPicker>
      </ElFormItem>
      <ElFormItem v-if="statisticalType" label="统计类型">
        <DictionaryPicker
          disabled
          code="TONG_JI_LEI_XING"
          :model-value="statisticalType"
          clearable
        ></DictionaryPicker>
      </ElFormItem> -->
      <!-- <ElFormItem
        v-if="virtually"
        label="是否虚拟类型"
        prop="isVirtually"
        clearable
      >
        <ElRadioGroup v-model="formData.isVirtually">
          <ElRadio :label="0" border>否</ElRadio>
          <ElRadio :label="1" border>是</ElRadio>
        </ElRadioGroup>
      </ElFormItem> -->
      <!-- <template
        v-if="formData.isVirtually === 0 || !virtually"
      > -->
      <!-- <ElDivider>参数</ElDivider> -->
      <ElFormItem
        v-if="statisticalType !== '2' && false"
        label="能源品种"
        prop="energyId"
      >
        <ElSelect
          v-model="formData.energyId"
          filterable
          placeholder="请选择能源品种"
          class="width-fill"
          clearable
        >
          <ElOption
            v-for="item in energyDiscountData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
            <span style="float: left">
              {{ item.name }}
            </span>
            <span
              style="
                float: right;
                color: var(--el-text-color-secondary);
                font-size: 13px;
              "
            >
              {{
                item.discountFactor
                  || item.referenceCoefficient
              }}
            </span>
          </ElOption>
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="单位" prop="unitId">
        <el-cascader
          v-model="formData.unitId"
          :options="unitData"
          :props="{
            label: 'unitName',
            value: 'id',
            children: 'unitList',
            emitPath: false,
          }"
          clearable
          class="width-fill"
          @change="handleUnitChange"
        />
      </ElFormItem>
      <ElFormItem label="倍率" prop="indicatorMultiple">
        <ElInputNumber
          v-model="formData.indicatorMultiple"
          :min="1"
          :max="100000"
          :step="1"
          step-strictly
          style="width: 160px;"
        />
      </ElFormItem>
    </ElForm>
  </CustomDialog>
</template>
